import Session from '../Session'
import * as _mysql from 'mysql'

import Config from '../../Config'

export default class MySQL extends Session {

    private _Promise: Promise<any>;

    constructor() {
        super();
        //加载  
        this.init();
    }

    private tractSQL(sql, _param) {
        var matchReg = /#.*#/gi;
        let _paramArray = [];
        var params = sql.match(matchReg);
        if (params && params.length > 0) {
            let _pp = params[0];
            let __pp = _pp.split(',');
            __pp.forEach(el => {
                if (el) {
                    sql = sql.replace(el, "?");
                    el = el.substring(1, el.length - 1);
                    _paramArray.push(_param[el]);
                }
            });
        }
        return [sql, _paramArray];
    }

    private init() {
        let self = this;
        this._Promise = new Promise(function (resolve, reject) {
            let _Connection = _mysql.createConnection(Object.assign(Config.mysql, { multipleStatements: true }));
            _Connection.connect(null, function (error, _connect) {
                if (error) {
                    console.log("MySQL Engine Connect Failure", error);
                } else {
                    console.log("MySQL Engine Connect Successful");
                }
                resolve(_Connection)
            });
        })

    }

    executeSQL(sql: string, params: any): Promise<any> {
        let _temp = this.tractSQL(sql, params[0]);
        let _sql = _temp[0];
        let _params = _temp[1];
        return this._Promise.then(function (_connection) {
            return new Promise(function (resolve, reject) {
                _connection.query(_sql, _params, function (err, rows, fields) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(rows);
                    }
                });
            })
        })
    }
}